﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using NGroup.VTL.Core.Utilities;

namespace NGroup.VTL.Web.Controllers
{
    public class UploadController : Controller
    {
        //
        // GET: /Upload/

        public ActionResult Index()
        {
            return View();
        }

        const string UploadPath = "/Upload/images/images/";
        const string logoImageFile = "/Content/images/logo.gif";
        const int marginBottom = 5;
        const int marginRight = 5;
        const int transparency = 80;
        [HttpPost]
        public JsonResult UploadUsingCK(HttpPostedFileBase fileToUpload)
        {
            string resultIconUrl = "";
            // Check xem phải có file được submit
            if (fileToUpload != null && fileToUpload.ContentLength > 0)
            {
                // Biến lưu tên file
                var fileName = Path.GetFileName(fileToUpload.FileName);
                fileName = CommonFunction.removeAccent(fileName);
                fileName = fileName.Replace(" ","-");
                string[] fileParts = fileName.Split(new char[] { '.' });
                if (fileParts.Length > 1)
                {
                    fileName = getFileNameNotExist(fileParts[fileParts.Length - 2], fileParts[fileParts.Length - 1]);
                }
                else {
                    return Json(new { url = "Wrong file!" }, JsonRequestBehavior.AllowGet);
                }

                //Lấy địa chỉ của ảnh IconUrl
                resultIconUrl = UploadPath + fileName;
                // Lưu file vào [UploadPath]
                var path = Path.Combine(Server.MapPath("~" + UploadPath), fileName);
                fileToUpload.SaveAs(path);
                Watermark.CreateWatermark(path,logoImageFile,marginBottom,marginRight,transparency);
            }
            return Json(new { url = resultIconUrl }, JsonRequestBehavior.AllowGet);
        }

        private string getFileNameNotExist(string name, string type)
        {
            string source = name + "." + type;
            if (System.IO.File.Exists(Server.MapPath("~" + UploadPath + source)))
            {
                string[] nameParts = name.Split(new char[] { '_' });
                if (nameParts.Length > 1)
                {
                    long count = 0;
                    long.TryParse(nameParts[2], out count);
                    count++;
                    name = nameParts[0] + "_" +count.ToString();
                }
                else
                {
                    name = name + "_1";
                }
                source = getFileNameNotExist(name,type);
            }
            return source;
        }

    }
}
